﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using Agility.Wcf.ClientProxy;
using Agility.Office.ExcelAddIn.Properties;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.ComponentModel;
using Agility.Wcf.ClientProxy.RequirementsManagementServiceClient;

namespace Agility.Office.ExcelAddIn
{
    public partial class ThisAddIn
    {
        private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private AgilityClientProxy proxy;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            this.logger.Debug("--> Entering ThisAddIn_Startup");
            proxy = AgilityClientProxy.GetInstance(new Uri(Properties.Settings.Default.AgilityUrl));
            this.logger.Debug("<-- Leaving ThisAddIn_Startup");
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            this.logger.Debug("--> Entering ThisAddIn_Shutdown");
            this.proxy.Dispose();
            this.logger.Debug("<-- Leaving ThisAddIn_Shutdown");
        }

        internal void AddTableMyIdeas(List<Epic> myIdeas)
        {
            this.logger.Debug("--> Entering AddTableMyIdeas");
            myIdeas = myIdeas.OrderBy(e => e.CreationDate).ThenBy(e => e.Title).ToList();
            Excel.Range topLeft = this.Application.ActiveCell;
            int row = topLeft.Row;
            int col = topLeft.Column;
            this.Application.ActiveSheet.Cells[row, col] = "Id";
            this.Application.ActiveSheet.Cells[row, col + 1] = "Title";
            this.Application.ActiveSheet.Cells[row, col + 2] = "Description";
            this.Application.ActiveSheet.Cells[row, col + 3] = "Date added";
            int i = 1;
            foreach (Epic idea in myIdeas)
            {
                this.Application.ActiveSheet.Cells[row + i, col] = idea.Id.ToString();
                this.Application.ActiveSheet.Cells[row + i, col].Locked = true;
                this.Application.ActiveSheet.Cells[row + i, col + 1] = idea.Title;
                this.Application.ActiveSheet.Cells[row + i, col + 2] = idea.Description;
                this.Application.ActiveSheet.Cells[row + i, col + 3] = idea.CreationDate;
                i++;
            }
            logger.Debug("Inserted ideas on the worksheet");
            Excel.Range tableRange = topLeft.Resize[myIdeas.Count + 1, 4];
            Excel.ListObject tableMyIdeas = this.Application.ActiveSheet.ListObjects.Add(Excel.XlListObjectSourceType.xlSrcRange, tableRange, false, Excel.XlYesNoGuess.xlYes);
            tableMyIdeas.Name = "TableMyIdeas";
            tableMyIdeas.ShowTableStyleRowStripes = true;
            tableMyIdeas.ListColumns.Item["Id"].Range.EntireColumn.Hidden = true;
            logger.Info("Created the table with MyIdeas");
            this.Application.ActiveSheet.Protect(string.Empty);
            logger.Debug("Protected the worksheet");
            this.logger.Debug("<-- Leaving AddTableMyIdeas");
        }

        internal void PublishChanges()
        {
            this.logger.Debug("--> Entering PublishChanges");
            try
            {
                Excel.ListObject tableMyIdeas = this.Application.ActiveSheet.ListObjects["TableMyIdeas"];
                List<Epic> myIdeas = new List<Epic>();
                int colCreationDate = tableMyIdeas.ListColumns["Date added"].Index;
                int colTitle = tableMyIdeas.ListColumns["Title"].Index;
                int colDescription = tableMyIdeas.ListColumns["Description"].Index;
                for (int i = 1; i <= tableMyIdeas.ListRows.Count; i++)
                {
                    Epic epic = new Epic();
                    if (string.IsNullOrEmpty(tableMyIdeas.DataBodyRange[i, colCreationDate].Text))
                    {
                        epic.CreationDate = DateTime.Parse(tableMyIdeas.DataBodyRange[i, colCreationDate].Text);
                    }
                    else
                    {
                        epic.CreationDate = DateTime.Today;
                    }
                    epic.Description = tableMyIdeas.DataBodyRange[i, colDescription].Text;
                    if (string.IsNullOrEmpty(tableMyIdeas.DataBodyRange[i, colTitle].Text))
                    {
                        // TODO: implement error notification
                        logger.Debug("Abort publishing because idea has no title");
                        return;
                    }
                    else
                    {
                        epic.Title = tableMyIdeas.DataBodyRange[i, colDescription].Text;
                    }
                    epic.RequestedBy = Settings.Default.UserName;
                    myIdeas.Add(epic);
                }
                this.proxy.SubmitChanges(myIdeas);
            }
            catch (COMException)
            {
                // TODO: implement error handling 
            }
            this.logger.Debug("<-- Leaving PublishChanges");
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}
